<!--
数据
{
   projectUuid:"2c9fe31d79d0fba10179d0fea5be0000",
   stage:"api",//api|db
   apiUuid:"",
   tableUuid:""
}
-->

<template>
    <el-form class="mc-api-origin">
       <el-tabs v-model="form.stage" @tab-click="tabClick">
         <el-tab-pane label="库表" name="db" v-if="showDb">
            <el-form-item>
                <el-input size="mini" placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
            </el-form-item>
            <el-form-item>
                <el-row>
                    <el-col :span="23">
                        <el-tree node-key="uuid" ref="selectTree" :data="treeList" default-expand-all style="overflow-y:scroll;"
                          :style="{maxHeight:maxHeight}"
                                :filter-node-method="filterNode" :highlight-current="true"
                                 @node-click="handleNodeClick" :props="defaultProps"></el-tree>
                    </el-col>
                    <el-col :span="1"><i style="cursor: pointer;" @click="resetChoose(true)" class="el-icon-delete"></i></el-col>
                </el-row>
            </el-form-item>
         </el-tab-pane>
          <el-tab-pane label="API列表" name="api" v-if="showApi">
            <el-form-item label="接口" label-width="40px">
              <el-select v-model="form.apiUuid" @change="changeApi" size="mini" :filterable="true">
                <el-option v-for="(item,idx) in apiList" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
              <i style="cursor: pointer;" @click="resetChoose(true)" class="el-icon-delete"></i>
            </el-form-item>
          </el-tab-pane>
       </el-tabs>
    </el-form>



</template>

<script>
import request from '../utils/request';
export default {
    name: 'mc-api-origin',
    data () {
        return {
            form:this.data,
            treeList:[],
            defaultProps: {
                children: 'children',
                label: 'name',
            },
            filterText:"",
            apiList:[],
            javaTypes : {
              Boolean:"Boolean",
              String:"String",
              Integer:"Integer",
              Date:"Date",
              Long:"Long",
              "Byte[]":"Byte[]",
              StringArray:"List<String>",
              LongArray:"List<Long>",
              "List<String>":"List<String>",
              "List<Long>":"List<Long>",
              BigDecimal:"BigDecimal",
              Double:"Double",
              Object:"Object",
              Float:"Float",
              Time:"Time",
              Timestamp:"Timestamp",
            },
            defaultTagToJavaType : {
              "mc-switch" : "Boolean",
              "el-slider" : "Integer",
              "el-date-picker" : "Date",
              "mc-date-picker" : "Date",
              "mc-rate" : "Integer",
              "el-rate" : "Integer",
              "el-input-number" : "Integer"
            }
        }
    },
    props:{
      data:{type:Object,default:null},
      projectUuid:{type:String,default:null},
      showApi:{type:Boolean,default:true},
      showDb:{type:Boolean,default:true},
      /*是否显示表下的字段*/
      showFields:{type:Boolean,default:false},
      maxHeight:{type:String,default:"300px"},
    },
    watch: {
      filterText(val) {
        this.$refs.selectTree.filter(val);
      }
    },
    mounted () {
       var _t = this;
       request.axios({$vue:_t,method:"get",url:"magical_lowcode/user/database/list",params:{projectUuid:_t.projectUuid}}).then(function(res) {
           _t.treeList = res.data;
           /*
           关闭记忆功能 加上反而用户不会清除 改变了url
           if(_t.form.stage=='db' && _t.form.tableUuid){
           _t.$nextTick(() => {
            //记忆功能 可能会找不到 导致报错
             _t.$refs.selectTree.setCurrentKey(_t.form.tableUuid);
             _t.clickCurrentNode();
           })
           }*/
       }).catch(function (error) {
           console.log(error)
       });
      request.axios({$vue:_t,method:"get",url:"magical_lowcode/user/api/list",params:{projectUuid:_t.projectUuid}}).then(function(res) {
          _t.apiList = res.data;
          if(_t.form.stage=='api' && _t.form.apiUuid){
              _t.changeApi();
          }
      }).catch(function (error) {
          console.log(error)
      });
    },
    methods:{
        filterNode(value, data) {
          if (!value) return true;
          return data.name.indexOf(value) !== -1;
        },
        resetChoose(emit){
            this.$nextTick(() => {
            //记忆功能 可能会找不到 导致报错
             if(this.form.stage=='db'){
                this.$refs.selectTree.setCurrentKey(null);
                this.form.tableUuid = "";//更新值
               if(emit){
                 this.$emit("choose",{stage:"db",tableName:"",fields:[],database:{}});
               }
             }else if(this.form.stage=='api'){
                this.form.apiUuid = "";//更新值
               if(emit){
                 this.$emit("choose",{stage:"api",apiUuid:"",fields:[]})
               }
             }
           })
        },
        clickCurrentNode:function(){
             var data = this.$refs.selectTree.getCurrentNode();
             if(data == null){
                return;
             }
             var node = this.$refs.selectTree.getNode(data);
             this.handleNodeClick(data,node);
        }
        ,
        handleNodeClick:function(data,node){
            if(node.level==1 || node.level==3){
                return;//数据库 字段点击都不用管
            }
            var databaseUuid = '';
            var database = null;
            for(var i=0;i<this.treeList.length;i++){
                 var children = this.treeList[i].children;
                 if(children){
                      for(var j=0;j<children.length;j++){
                           if(children[j].uuid == data.uuid){
                             databaseUuid=this.treeList[i].uuid;
                             database = this.treeList[i];
                             break;
                           }
                      }
                 }

            }
            var tableName = data.name;
            var _t = this;
            request.axios({$vue:_t,method:"get",url:"magical_lowcode/user/table/info",
                params:{projectUuid:_t.projectUuid,databaseUuid:databaseUuid,uuid:data.uuid}})
                .then(function(res) {
                var rootNode=res.data.data.rootNode;
                if(!rootNode){
                  rootNode= MAGICAL_CODER_API.htmlToRootNode({html:res.data.data.html,pure:true});
                }else{
                  rootNode = JSON.parse(rootNode);
                }
                var tableInfo = _t.tableToFields(rootNode);
                var fields = tableInfo.fields;
//                _t.$emit("choose",{url:"magical_lowcode/openapi/crud/"+tableName+"/list",fields})
                _t.form.tableUuid = data.uuid;//更新值
                _t.$emit("choose",{stage:"db",tableName,fields,database});
                if(_t.showFields){//处理动态增加表下字段列表
                    var treeFields = _t.treeChildrenData(tableName,fields);
                    _t.$set(data, 'children', treeFields);
                }
            }).catch(function (error) {
                console.log(error)
            });
        },
        treeChildrenData:function(tableName,fields){
            var list = [];
            if(fields){
                for(var i=0;i<fields.length;i++){
                  var field = fields[i];
                  if(field.name===field.title){
                      list.push({name:field.name,uuid:tableName+field.name})
                  }else{
                      list.push({name:field.name+" ["+field.title+"]",uuid:tableName+field.name})
                  }
                }
            }
            return list;
        },
        tableToFields:function(rootNode){
            var tableInfo = {};
            //字段信息
            var tableFields = [];//{name:"",type:"",len:2,defaultValue:"",pk:false,notNull:true,autoInc:false,comment:""}
            var children = rootNode.magicalCoder.children;
            if(children){
              for(var i=0;i<children.length;i++){
                var field = {};
                var fieldParent = null;
                var elFormItem = children[i];
                var attributes = elFormItem.attributes;
                var magicalCoder = elFormItem.magicalCoder;
                if(magicalCoder.tagName !== 'el-form-item'){
                  layer.alert("检测到存在控件不在标题控件内，请放入标题控件后再尝试");
                  return null;
                }
                //注释
                field.comment = attributes.label;
                field.title = attributes.label;
                {//寻找包含的控件
                  if(magicalCoder.children){
                    var controlNode = magicalCoder.children[0]
                    var controlAttributes = controlNode.attributes;
                    var controlMagicalCoder = controlNode.magicalCoder;
                    var tagName = controlMagicalCoder.tagName;
                    var vModel = controlAttributes['v-model'];
                    field.name = vModel;
                    if(!vModel){
                      field.name = controlAttributes[':data.sync'];//其他自定义的组件 暂时取这个名字
                    }
                    var javaType = controlAttributes['mc-java-type'];
                    if(javaType){
                      field.javaType = javaType.replace("&lt;","<").replace("&gt;",">");
                    }else{
                      field.javaType = this.toJavaType(controlNode);
                    }
                    //小数Bigdecimal
                    {
                      if(field.javaType==this.javaTypes.BigDecimal){
                        field.scale = controlAttributes[':precision'];
                        field.precision = controlAttributes['mc-length']||19;//默认的
                      }
                    }
                    var pkType = controlNode.attributes['mc-pk-type'];//主键类型
                    field.pkType = pkType;
                    if(pkType){//存在主键 把主键信息保留
                      tableInfo.pk = field;
                      if(pkType=='IDENTITY'){
                        field.javaType = this.javaTypes.Long;
                      }else if(pkType=='UUID'){
                        field.javaType = this.javaTypes.String;
                      }
                    }
                    var dbType = controlNode.attributes['mc-db-type'];//数据库类型
                    if(!dbType){
                      if(tagName=='mc-kindeditor'){
                        dbType = 'clob';
                      }
                    }
                    field.dbType = dbType;
                    //
                    var dbName = controlAttributes['mc-db-name'];
                    field.dbName = dbName;
                    //column
                    var mcColumnWebUserId = controlAttributes['mc-column-web-user-id'];
                    if(mcColumnWebUserId==='true'){
                      field.webUserId = true;
                    }else{
                      field.webUserId = false;
                    }
                    //检测是不是父子下拉框 父子下拉框 2个字段合并在一个组件了
                    if(tagName==='mc-parent-child-select'){
                      //检测父亲下拉框是否配置字段
                      var pmodel = controlAttributes[':p-model.sync'];
                      if(pmodel){
                        var fieldParent = {name:pmodel};
                        var parentJavaType = controlAttributes['mc-parent-java-type'];
                        if(parentJavaType){
                          fieldParent.javaType = parentJavaType;
                        }else{
                          fieldParent.javaType = this.toJavaType(controlNode);
                        }
                        fieldParent.comment = controlAttributes['mc-parent-comment']||pmodel;
                        fieldParent.title = controlAttributes['mc-parent-comment']||pmodel;
                        field.comment = controlAttributes['mc-child-comment']||vModel;
                        field.title = controlAttributes['mc-child-comment']||vModel;
                        tableFields.push(fieldParent);
                      }
                    }
                    else if(tagName == 'mc-parent-child-grandson-select'){
                      //检测父亲下拉框是否配置字段
                      var pmodel = controlAttributes[':p-model.sync'];
                      if(pmodel){
                        var fieldParent = {name:pmodel};
                        var parentJavaType = controlAttributes['mc-parent-java-type'];
                        if(parentJavaType){
                          fieldParent.javaType = parentJavaType;
                        }else{
                          fieldParent.javaType = this.toJavaType(controlNode);
                        }
                        fieldParent.comment = controlAttributes['mc-parent-comment']||pmodel;
                        fieldParent.title = controlAttributes['mc-parent-comment']||pmodel;
                        tableFields.push(fieldParent);
                      }
                      //检测父亲下拉框是否配置字段
                      var cmodel = controlAttributes[':c-model.sync'];
                      if(cmodel){
                        var fieldChild = {name:cmodel};
                        var childJavaType = controlAttributes['mc-child-java-type'];
                        if(childJavaType){
                          fieldChild.javaType = childJavaType;
                        }else{
                          fieldChild.javaType = this.toJavaType(controlNode);
                        }
                        fieldChild.comment = controlAttributes['mc-child-comment']||cmodel;
                        fieldChild.title = controlAttributes['mc-child-comment']||cmodel;
                        field.comment = controlAttributes['mc-grandson-comment']||vModel;
                        field.title = controlAttributes['mc-grandson-comment']||vModel;
                        tableFields.push(fieldChild);
                      }

                    }
                  }
                }
                //清除下 换行 空格之类的
                for(var key in field){
                  var value = field[key];
                  if(typeof value =='string' && value){
                    value = value.replace(/[\t\n\r]+/g,"");
                    field[key]=value;
                  }
                }
                tableFields.push(field);
              }
            }
            {
                for(var i=0; i<tableFields.length; i++){
                    for(var j=i+1; j<tableFields.length; j++){
                        if(tableFields[i].name==tableFields[j].name){         //第一个等同于第二个，splice方法删除第二个
                            tableFields.splice(j,1);
                            j--;
                        }
                    }
                }
            }
            tableInfo.fields = tableFields;
            return tableInfo;
        },
        toJavaType : function(controlNode){
          var javaType = controlNode.attributes['mc-java-type'];
          if(javaType){
            return javaType.replace("&lt;","<").replace("&gt;",">");
          }
          var tagName = controlNode.magicalCoder.tagName;
          //decimal
          if(tagName=='el-input-number' && controlNode.attributes[':precision']){
            if(parseInt(controlNode.attributes[':precision'])>0){
              return this.javaTypes.BigDecimal;
            }
          }
          //数组类型处理下
          if(tagName=='mc-remote-select'||tagName=='mc-select'){
            var multiple = controlNode.attributes['multiple']||controlNode.attributes[':multiple'];
            if(multiple){
              return this.javaTypes.StringArray;
            }
          }

          return this.defaultTagToJavaType[tagName]||this.javaTypes.String;
        },
        changeApi:function(){
            this.$emit("choose",{stage:"api",apiUuid:this.form.apiUuid,fields:[]})
        },
        tabClick:function(){
            if(this.form.stage=='api'){
                this.changeApi();
            }else{
                this.clickCurrentNode();
            }
        }
    }
}
</script>

<style lang="scss">
.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: #409eff;
  color: white;
}
.el-tree-node.is-current
  > .el-tree-node__content {
  background-color: #409eff !important;
  color: white;
}
</style>
